package org.raymond.iworks.commons.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.util.StringTokenizer;

public class ErrorUtil {
    private final static Integer DEFAULT_THIRD_DEEP = 2;
    private final static Integer DEFAULT_APP_DEEP = 2;
    private ErrorUtil(){}

    public static String getErrorLog(Throwable e){
        String linebreak = System.lineSeparator();
        StringTokenizer frames = new StringTokenizer(getStackTrace(e), linebreak);
        StringBuilder sb = new StringBuilder();

        sb.append(frames.nextToken());
        for(int i=0; frames.hasMoreTokens() && i<DEFAULT_THIRD_DEEP; i++){
            sb.append(linebreak).append(frames.nextToken());
        }
        for(int i=0; frames.hasMoreTokens() && i<DEFAULT_APP_DEEP; ){
            String frame = frames.nextToken();
            if(StringUtils.indexOf(frame, "org.raymond")>0){
                sb.append(linebreak).append(frame);
                i++;
            }
        }

        String result = sb.toString();
        if(StringUtils.isBlank(result)){
            result = getRootCauseMessage(e);
        }

        return result;
    }

    public static String getRootCauseMessage(Throwable t){
        return ExceptionUtils.getRootCauseMessage(t);
    }

    public static String getStackTrace(Throwable t){
        return ExceptionUtils.getStackTrace(t);
    }

    public static Throwable getRootCause(Throwable t){
        return ExceptionUtils.getRootCause(t);
    }
}
